#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>

#include "data_exchange.h"

static int msg_id;

int data_exchange_mqclear(void)
{
    if (msgctl(msg_id, IPC_RMID, 0) == -1)
    {
        perror("msgctl");
        return -1;
    }

    return 0;
}

int data_exchange_init(void)
{
    msg_id = msgget((key_t)WEB_MQ_KEY, IPC_CREAT | 0664);
    if (msg_id == -1)
    {
        perror("msgget");
        return -1;
    }

    return data_exchange_mqclear();
}

void data_exchange_getpwd(char *pwd)
{
    struct message
    {
        long mtype;
        char mtext[sizeof(mq_data_t)];
    };
    mq_data_t *mq_data;

    struct message new_msg;
    memset(&new_msg, 0, sizeof(new_msg));
    mq_data = (mq_data_t *)&new_msg.mtext;

    new_msg.mtype = EN_MSG_TYPE_WEB;
    mq_data->direction = EN_MSG_TYPE_APP;
    strcpy(mq_data->file_name, "get_password");
    msgsnd(msg_id, &new_msg, sizeof(new_msg.mtext), 0);

    usleep(50);
    memset(&new_msg, 0, sizeof(new_msg));

    /* msgrcv(msgid, &buf, sizeof(buf.mtext), 1, MSG_PEEK); MSG_PEEK 标志，查看消息*/
    msgrcv(msg_id, &new_msg, sizeof(new_msg.mtext), EN_MSG_TYPE_APP, 0 /*IPC_NOWAIT*/);
}

int data_exchange(const char *filename, const char *data, size_t size)
{
    mq_data_t *mq_data;
    ssize_t ret;

    msg_id = msgget((key_t)WEB_MQ_KEY, IPC_CREAT | 0664);
    if (msg_id == -1)
    {
        perror("msgget");
        return -1;
    }

    struct message
    {
        long mtype;
        char mtext[sizeof(mq_data_t)];
    };
    struct message new_msg;

    printf("data_exchange:%s, date size:%d", filename, size);
    if (!filename || size > sizeof(mq_data_t))
    {
        return -1;
    }

    memset(&new_msg, 0, sizeof(new_msg));
    mq_data = (mq_data_t *)new_msg.mtext;

    new_msg.mtype = EN_MSG_TYPE_WEB;
    mq_data->direction = EN_MSG_TYPE_APP;
    strcpy(mq_data->file_name, filename);
    if (size)
        strncpy(mq_data->data, data, size);

    printf("11111111111111\n");
    msgsnd(msg_id, &new_msg, sizeof(new_msg.mtext), 0);

    usleep(50);
    memset(&new_msg, 0, sizeof(new_msg));
    printf("2222222222222222222222\n");
    /*  msgrcv(msgid, &buf, sizeof(buf.mtext), 1, MSG_PEEK); MSG_PEEK 标志，查看消息 */
    ret = msgrcv(msg_id, &new_msg, sizeof(new_msg.mtext), EN_MSG_TYPE_APP, 0 /*IPC_NOWAIT*/);
    printf("33333333333333333333:%d\n", ret);

    web_response(mq_data->proc_status, mq_data->data);

    return 0;
}

/* 在页面超时加消息队列清空处理，以免消息队列导致内存耗尽 */